package com.shared_file_bucket.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shared_file_bucket.common.properties.FsServerProperties;
import com.shared_file_bucket.common.utils.StringUtils;
import com.shared_file_bucket.model.ShareDir;
import com.shared_file_bucket.model.User;
import com.shared_file_bucket.service.ShareDirService;
import com.shared_file_bucket.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequiredArgsConstructor
public class IndexController {

    private final UserService userService;

    private final FsServerProperties fsServerProperties;

    private final ShareDirService shareDirService;

    @GetMapping("/main")
    public String main(HttpServletRequest request, Model model, String dir, String shareCode) {
        if (!StpUtil.isLogin()) {
            // 保存原有页面的地址到sessionStorage中
            String returnUrl = getFullRequestUrl(request);
            request.getSession().setAttribute("returnUrl", returnUrl);
            return "redirect:/login";
        }
        Long userId = StpUtil.getLoginIdAsLong();
        User loginUser = userService.getById(userId);
        if (StringUtils.isEmpty(loginUser.getRoot())) {
            loginUser.setRoot(fsServerProperties.getLocal().getUploadDir());
        }
        // 登录用户信息
        model.addAttribute("loginUser", loginUser);
        if (StringUtils.isNotEmpty(shareCode)) {
            dir = shareDirService.getOne(new LambdaQueryWrapper<ShareDir>().eq(ShareDir::getUuid, shareCode)).getDirName();
        }
        model.addAttribute("thisDir", dir);
        return "main";
    }

    public String getFullRequestUrl(HttpServletRequest request) {
        // 获取请求的URL
        StringBuffer requestUrl = request.getRequestURL();
        // 获取请求的参数字符串
        String queryString = request.getQueryString();
        // 如果请求有参数，则将参数字符串添加到URL后面
        if (queryString != null) {
            requestUrl.append("?").append(queryString);
        }
        // 返回完整的请求地址
        return requestUrl.toString();
    }

    /**
     * 主页
     */
    @GetMapping({"", "/index"})
    public String index(HttpServletRequest request, Model model) {
        if (!StpUtil.isLogin()) {
            return "redirect:/login";
        }
        Long userId = StpUtil.getLoginIdAsLong();
        User loginUser = userService.getById(userId);
        if (StringUtils.isEmpty(loginUser.getRoot())) {
            loginUser.setRoot(fsServerProperties.getLocal().getUploadDir());
        }
        // 登录用户信息
        model.addAttribute("loginUser", loginUser);

        // 判断是否存在returnUrl参数
        String returnUrl = (String) request.getSession().getAttribute("returnUrl");
        if (returnUrl != null) {
            // 存在returnUrl参数，将其作为重定向地址返回给前端
            request.getSession().removeAttribute("returnUrl");
            return "redirect:" + returnUrl;
        } else {
            // 不存在returnUrl参数，返回默认的重定向地址
            return "shareDir";
        }
    }

    @GetMapping("/fileChoose")
    public String fileChoose() {

        return "fileChoose";
    }

    /**
     * 错误页
     */
    @RequestMapping("/error/{code}")
    public String error(@PathVariable("code") String code) {
        if ("403".equals(code)) {
            return "error/403";
        } else if ("500".equals(code)) {
            return "error/500";
        }
        return "error/404";
    }
}
